<%@ page import="java.awt.*" %>
<%@ page import="java.util.Random" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="javax.imageio.ImageIO" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2016/6/10 0010
  Time: 上午 8:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%!
    public static String code = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
    //获得随机颜色
    Color getRandColor (int fc,int bc){
        Random random = new Random();
        if(fc > 255) {
            fc = 255;
        }
        if(bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r,g,b);
    }
%>
<%
  //设置页面不缓存
    response.setHeader("Pragma","No-cache");
    response.setHeader("Cache-Control","no-cache");
    response.setDateHeader("Expires",0);

    //在内存中创建对象，设置图片的显示大小
    int width = 80;
    int height = 40;
    BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
    //BufferedImage.TYPE_3BYTE_BGR  生成的图片最小

    //获得图形上下文
    Graphics g =image.getGraphics();
    //生成随机类
    Random random = new Random();
    //设置背景颜色
    //g.setColor(getRandColor(100,150));
    g.fillRect(0,0,width,height);
    //设置字体
    g.setFont(new Font(("Times New Roman"),Font.PLAIN,22));
    //设置边框

    //生成随机干扰线
    g.setColor(getRandColor(100,150));
    for(int i = 0;i < 60;i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xx = random.nextInt(12);
        int yy = random.nextInt(12);
        g.drawLine(x,y,x+xx,y+yy);
    }
    //取随机产生的验证码
    String sRand = "";
    for(int i = 0;i <= 4;i++){
        int rand = random.nextInt(62);
        sRand += String.valueOf(code.charAt(rand));
        //将验证码显示到图像中
        g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
        g.drawString(String.valueOf(code.charAt(rand)),13*i+6,16);

    }
    //将验证码存入session中
    session.setAttribute("rand",sRand);
    g.dispose();
    //输出图像到页面中
    ImageIO.write(image,"JPEG",response.getOutputStream());
%>